package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.dto.UserSearchDTO;
import com.heima.search.service.ArticleSearchService;
import com.heima.search.vo.SearchArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lo
 * @date 2021/10/9
 */
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    public static final String ARTICLE_INDEX_NAME = "app_info_article";

    @Autowired
    EsService<SearchArticleVO> esService;

    @Value("${file.minio.readPath}")
    String readPath;
    @Override
    public ResponseResult search(UserSearchDTO dto) {
        //1.校验参数
        if (dto==null|| StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }

        //2.封装条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //封装搜索词
        boolQueryBuilder.must(QueryBuilders.matchQuery("title",dto.getSearchWords()));

        // 发布最小时间过滤
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime()));
        //设置每页显示记录数
        builder.from(0);
        builder.size(dto.getPageSize());

        //发布时间排序
        builder.sort("publishTime", SortOrder.DESC);

        //设置高亮(高亮字段,高亮前缀,高亮后缀)
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");

        builder.highlighter(highlightBuilder);
        builder.query(boolQueryBuilder);
        //3 执行查询解析结果
        PageResponseResult pageResponseResult = esService.search(builder, SearchArticleVO.class, ARTICLE_INDEX_NAME);
        List<SearchArticleVO> searchArticleVOS = JSON.parseArray(JSON.toJSONString(pageResponseResult.getData()), SearchArticleVO.class);
        //4 封装结果并返回,处理静态文件的前缀
        //设置静态资源路径
        List<SearchArticleVO> collect = searchArticleVOS.stream().map(searchArticleVO -> {
            searchArticleVO.setStaticUrl(readPath + searchArticleVO.getStaticUrl());
            return searchArticleVO;
        }).collect(Collectors.toList());
        return ResponseResult.okResult(collect);
    }
}
